package com.rogers.rmcdouga.skirmishgadget.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.SpanElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ErrorEvent;
import com.google.gwt.event.dom.client.ErrorHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.LoadEvent;
import com.google.gwt.event.dom.client.LoadHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.gen2.logging.shared.Log;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.rogers.rmcdouga.skirmishgadget.client.java.util.UUID;

public class ImageURLBox extends Composite
{

	private static URLBoxUiBinder uiBinder = GWT.create(URLBoxUiBinder.class);

	interface URLBoxUiBinder extends UiBinder<Widget, ImageURLBox> {}

	private HandlerManager changeHandlerManager = null; 
	
	interface URLBox_ValidityCallback
	{
		void validURL();
		void invalidURL();
	}
	
	private URLBox_ValidityCallback callback = null;
	private String invisibleImageContainerID;
	private boolean validURL;
	
	@UiField
	SpanElement invisibleImageContainer;
	
	@UiField
	InlineLabel urlCaption;

	@UiField
	Button testURLButton;

	@UiField
	TextBox urlTextBox;
	private Image image = null;

	public Image getImage()
	{
		return image;
	}

	public String getUrlCaption()
	{
		return urlCaption.getText();
	}

	public void setUrlCaption(String urlCaption)
	{
		this.urlCaption.setText(urlCaption);
	}

	private Button getTestURLButton()
	{
		return testURLButton;
	}

	private void setTestURLButton(Button testURLButton)
	{
		this.testURLButton = testURLButton;
	}

	private TextBox getUrlTextBox()
	{
		return urlTextBox;
	}

	private void setUrlTextBox(TextBox urlTextBox)
	{
		this.urlTextBox = urlTextBox;
	}

	public @UiConstructor ImageURLBox(String urlCaption) {
		initWidget(uiBinder.createAndBindUi(this));
		this.urlCaption.setText(urlCaption);	// Initialize the caption
		
		// Generate the ID for the invisible image container for this dialog.
		invisibleImageContainerID = UUID.randomUUID().toString();
		invisibleImageContainer.setId(invisibleImageContainerID);
	}

	@UiHandler("urlTextBox")
	void UrlTextBox_KeyPress(KeyPressEvent e)
	{
		setValidURL(false);
	}
	

	@UiHandler("urlTextBox")
	void UrlTextBox_KeyDown(KeyDownEvent e)
	{
		int nativeKeyCode = e.getNativeKeyCode();
		if (nativeKeyCode == KeyCodes.KEY_BACKSPACE || nativeKeyCode == KeyCodes.KEY_DELETE)
			setValidURL(false);
	}
	

	@UiHandler("testURLButton")
	void onClick(ClickEvent e)
	{
		Log.info("ImageURLBox click event handler - UrlValue='" + urlTextBox.getText() + "'.");
		checkUrl();

	}

	private void checkUrl()
	{
		image = new Image();
		image.addLoadHandler(new LoadHandler()
		{
			public void onLoad(LoadEvent event) {
				Log.info("Inside ImageURLBox Image Load event handler");
				setValidURL(true);
			}
		}
		);
		image.addErrorHandler(new ErrorHandler()
		{
			public void onError(ErrorEvent event) {
				Log.info("Inside ImageURLBox Image Error event handler");
				setValidURL(false);
			}
		}
		);

		image.setUrl(urlTextBox.getText());
		// Do to a bug in GWT (http://code.google.com/p/google-web-toolkit/issues/detail?id=863), images are not loaded
		// until they are attached to the DOM, so we need to add the image into an invisible container/
		RootPanel.get(invisibleImageContainerID).add(image);
	}

	/**
	 * This method sets a callback interface that is invoked whenever the Check URL button is pressed.
	 * The method that is called is called depends on whether the URL was valid or not.
	 * 
	 *  This method queues a call to the CheckUrl() function using DeferredCommand so that the initial state
	 *  can be set.
	 * 
	 * @param callback
	 */
	public void setCallback(URLBox_ValidityCallback callback)
	{
		this.callback = callback;
		// Need to defer the "checkURL()" call until everything's initialized.
		DeferredCommand.addCommand(new Command(){
			public void execute() {
				checkUrl();
			}
		});
	}

	public String getUrl()
	{
		return urlTextBox.getText();
	}

	public void setUrl(String url)
	{
		this.urlTextBox.setText(url);
		// Need to defer the "checkURL()" call until everything's initialized.
		DeferredCommand.addCommand(new Command(){
			public void execute() {
				checkUrl();
			}
		});
	}

	public boolean isValidURL()
	{
		return validURL;
	}

	private void setValidURL(boolean validURL)
	{
		this.validURL = validURL;
		if (callback != null)
		{
			if (validURL == true)
				callback.validURL();
			else
				callback.invalidURL();
		}
		Log.info("Inside setValidURL, validURL=" + validURL +".");
	}

}
